<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\RechargeRecord;
use app\madmin\model\UserCash as admin;
use app\shop_admin\model\IntegralRecord;
use app\utils\TrimData;
use think\Exception;
use think\facade\Db;

class UserCashService
{

    private $user;

    public function __construct()
    {
        global $user;
        $this->user = $user;
    }

    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function findAll(array $data, int $page = 1, int $size = 10)
    {

        $admin = admin::with('user');
        $admin = TrimData::searchDataTrim($admin, $data, ['begin_date', 'end_date']);

        $list = $admin->where($data)->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 读取一条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = admin::find($id);
        return [HTTP_SUCCESS, $model];
    }

    /**
     * 商户
     * @param int $page
     * @param int $size
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function merchantFindAll(int $page, int $size,array $data){
        $where = [];
        if (!empty($data['type']))$where[] = ['type','=',$data['type']];
        if (!empty($data['start_time']))$where[] = ['create_time','>=',$data['start_time']];
        if (!empty($data['end_time']))$where[] = ['create_time','<=',$data['end_time']];
        $select = Db::name('merchant_log')
            ->where($where)
            ->where('mall_id',$this->user['mall_id'])
            ->paginate(['page' => $page,'list_rows' => $size]);
        return [HTTP_SUCCESS,$select];
    }


    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return array
     */
    public function update(int $id, array $data)
    {
        $update_time = $data['update_time'];
        unset($data['update_time']);
        $admin = admin::where('update_time', $update_time)
            ->where('user_id', $id)
            ->save($data);
        return [HTTP_CREATED, $admin];
    }

    /**
     * 积分修改
     * @param int $id
     * @param array $data
     * @return array
     * @throws Exception
     */
    public function integral(int $id, array $data)
    {
        if($this->user->affiliation == 'saas') {
            $admin = Db::name('saas_admin')->where('id', $this->user->id)->find();
        }else if($this->user->affiliation == 'suser') {
            $admin = Db::name('saas_user')->where('id', $this->user->id)->find();
        }else{
            $admin = \app\madmin\model\Admin::where('status', 1)->where('id', $this->user->id)->find()->toArray();
        }
        if (!$admin || hash('sha256', $data['password']) != $admin['password'])
            throw new Exception("密码错误", HTTP_NOTACCEPT);
        if (!is_integer($data['num']) || $data['num'] < 0)
            throw new Exception('积分必须是正整数',HTTP_INVALID);
        $update_time = $data['update_time'];
        unset($data['update_time']);
        $integral = $data['num'];
        switch ($data['type']) {
            case 0:
                $admin = admin::where(['update_time' => $update_time, 'user_id' => $id])->inc('integral_total',$data['num'])->inc("integral", $data['num'])->save();
                if (!empty($admin)) $type = 4;
                break;
            case 1:
                $new_integral = admin::where(['update_time' => $update_time, 'user_id' => $id])->value('integral');
                if ($integral > $new_integral)
                    throw new Exception('不能把积分调整为负数',HTTP_NOTACCEPT);
                $admin = admin::where(['update_time' => $update_time, 'user_id' => $id])->dec("integral", $data['num'])->save();
                if (!empty($admin))$type = 5;
                break;
            case 2:
                $integral = admin::where('user_id',$id)->value('integral');
                $admin = admin::where(['update_time' => $update_time, 'user_id' => $id])->save(["integral" => $data['num']]);
                if (!empty($admin)) {
                    if ($integral > $data['num']){
                        $type = 5;
                        $integral = $integral - $data['num'];
                    }else{
                        $type = 4;
                        $integral = $data['num'] - $integral;
                    }
                }
                break;
        }
        IntegralRecord::create([
            'user_id' => $id,
            'mall_id' => $this->user->mall_id,
            'order_id' => 0,
            'commodity_id' => 0,
            'sku_id' => 0,
            'number' => 0,
            'type' => $type,
            'status' => 1,
            'integral' => $integral,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s')
        ]);
        return [HTTP_CREATED, $admin];
    }

    public function recharge(int $id, array $data)
    {
        if($this->user->affiliation == 'saas') {
            $admin = Db::name('saas_admin')->where('id', $this->user->id)->find();
        }else if($this->user->affiliation == 'suser') {
            $admin = Db::name('saas_user')->where('id', $this->user->id)->find();
        }else{
            $admin = \app\madmin\model\Admin::where('status', 1)->where('id', $this->user->id)->find()->toArray();
        }
        if (!$admin || hash('sha256', $data['password']) != $admin['password'])
            throw new Exception("密码错误", HTTP_NOTACCEPT);

        if ($data['amount'] < 0)
            throw new Exception('输入的金额不能小于0',HTTP_NOTACCEPT);
        $total = admin::where('user_id',$id)->value('total');
        if ($data['type'] == 1){
            if ($total < $data['amount'])
                throw new Exception('减少的金额不能大于用户实际余额',HTTP_NOTACCEPT);
        }
        $update_time = $data['update_time'];
        unset($data['update_time']);

        switch ($data['type']) {
            case 0:
                $admin = admin::where(['update_time' => $update_time, 'user_id' => $id])
                    ->inc("total", $data['amount'])
                    ->save();
                $reality = bcadd((string) $total,(string) $data['amount']);
                break;
            case 1:
                $admin = admin::where(['update_time' => $update_time, 'user_id' => $id])
                    ->dec("total", $data['amount'])
                    ->save();
                $reality = bcsub((string) $total,(string) $data['amount']);
                break;
            case 2:
                $admin = admin::where(['update_time' => $update_time, 'user_id' => $id])
                    ->save(["total" => $data['amount']]);
                $reality = $data['amount'];
                break;
        }

        if ($admin == 1){
            $recordData = [
                "user_id" => $id,
                'mall_id' => $this->user->mall_id,
                "base_in" => $this->user->username,
                "source_type" => 5,
                "source" => "后台变更",
                "type" => $data['type'],
                "money" => $data['amount'],
                "remark" => $data['remark'],
                "status" => 1,
                "old_cash" => $total,
                "new_cash" => $reality,
            ];
            RechargeRecord::create($recordData);
        }

        return [HTTP_CREATED, $admin];
    }

    /**
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        admin::destroy($id);
        return HTTP_NOCONTEND;
    }

}
